﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // ✅ 引入 Newtonsoft.Json
using System.Windows.Forms;
using SwParaPlatform2.logger;

namespace SwParaPlatform2.server
{
    public class HttpServerManager
    {
        private readonly HttpListener _listener;
        private readonly string _url;
        private bool _isRunning = false;

        public HttpServerManager(string url = "http://localhost:5001/receive/")
        {
            _url = url;
            _listener = new HttpListener();
            _listener.Prefixes.Add(_url);
        }

        public void Start()
        {
            if (!_isRunning)
            {
                _isRunning = true;
                Task.Run(() => RunServer());
                Logger.Instance.Log($"🚀 [C#] HTTP 服务器已启动，监听 {_url}");
            }
            else
            {
                Logger.Instance.Log("⚠ [C#] HTTP 服务器已在运行...");
            }
        }

        private void RunServer()
        {
            _listener.Start();
            while (true)
            {
                HttpListenerContext context = _listener.GetContext();
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;

                try
                {
                    using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        string json = reader.ReadToEnd();
                        var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); // ✅ 替换 System.Text.Json

                        Logger.Instance.Log("📨 [C#] Python 返回的文本: " + result["text"]);

                        // 解析字典
                        string dictJson = result["dict"].ToString();
                        var processedDict = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(dictJson); // ✅ 替换 System.Text.Json

                        Logger.Instance.Log("📨 [C#] Python 处理后的字典:");
                        foreach (var item in processedDict)
                        {
                            Logger.Instance.Log($"  - {item.Key}: {JsonConvert.SerializeObject(item.Value, Formatting.Indented)}"); // ✅ 替换 JsonSerializer.Serialize
                        }
                    }

                    // 响应 200 状态
                    response.StatusCode = 200;
                    response.OutputStream.Close();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log("❌ [C#] 解析 Python 返回值时出错: " + ex.Message);
                    response.StatusCode = 500;
                    response.OutputStream.Close();
                }
            }
        }
    }

    public class PythonCaller
    {
        private readonly string _pythonExe;
        private readonly string _scriptPath;

        public PythonCaller(string pythonExe = "python", string scriptPath = "model_link.py")
        {
            _pythonExe = pythonExe;
            _scriptPath = scriptPath;
        }

        public void SendDataToPython(string inputText, Dictionary<string, Dictionary<string, object>> paramDict)
        {
            // 🔹 1. 将字典转换为 JSON 字符串
            string paramDictJson = "";
            try
            {
                paramDictJson = JsonConvert.SerializeObject(paramDict, new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented, // ✅ 替换 WriteIndented
                    NullValueHandling = NullValueHandling.Ignore, // ✅ 替换 DefaultIgnoreCondition
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() // ✅ 替换 PropertyNamingPolicy.CamelCase
                });
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
                MessageBox.Show($"Error in TaskPaneHost_OpenConfigFileClick: {ex.Message}");
            }

            // 🔹 2. 调用 Python 脚本
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = _pythonExe,
                Arguments = $"\"{_scriptPath}\" \"{inputText}\" \"{paramDictJson}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8
            };

            using (Process process = new Process { StartInfo = psi })
            {
                process.Start();

                // 读取 Python 输出
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();

                Logger.Instance.Log("📤 [C#] 已发送数据到 Python");
                Logger.Instance.Log("📥 [C#] Python 输出: " + output);
                Logger.Instance.Log("❌ [C#] Python 错误: " + error);
            }

            Logger.Instance.Log("📤 [C#] 已发送数据到 Python");
        }
    }
}



